package com.platform.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.text.Convert;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.module.domain.BaseFactory;
import com.platform.module.domain.BaseValveData;
import com.platform.module.domain.BaseValveType;
import com.platform.module.mapper.BaseFactoryMapper;
import com.platform.module.mapper.BaseValveDataMapper;
import com.platform.module.mapper.BaseValveTypeMapper;
import com.platform.module.service.IBaseValveTypeService;
import com.platform.system.domain.SysDictData;
import com.platform.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 阀门型号数据Service业务层处理
 * 
 * @author wangqi
 * @date 2020-07-13
 */
@Service
public class BaseValveTypeServiceImpl extends ServiceImpl<BaseValveTypeMapper,BaseValveType> implements IBaseValveTypeService
{
    @Autowired
    private BaseValveTypeMapper baseValveTypeMapper;

    @Autowired
    private BaseFactoryMapper baseFactoryMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private BaseValveDataMapper baseValveDataMapper;
    /**
     * 查询阀门型号数据列表
     * 
     * @param baseValveType 阀门型号数据
     * @return 阀门型号数据
     */
    @Override
    public List<BaseValveType> selectBaseValveTypeList(BaseValveType baseValveType)
    {
        return baseValveTypeMapper.selectBaseValveTypeList(baseValveType);
    }
    /**
     * 查询子设备数量
     *
     * @param typeId 设备类型
     * @return 结果
     */
    @Override
    public int selectCountValveDataByTypeId(Long typeId)
    {
        return baseValveDataMapper.selectCount(new QueryWrapper<BaseValveData>().eq("type_id",typeId));
    }
    /**
     * 新增阀门型号数据
     * 
     * @param baseValveType 阀门型号数据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBaseValveType(BaseValveType baseValveType)
    {
        baseValveType.setCreateTime(DateUtils.getNowDate());
        return baseValveTypeMapper.insert(baseValveType);
    }

    /**
     * 修改阀门型号数据
     * 
     * @param baseValveType 阀门型号数据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBaseValveType(BaseValveType baseValveType)
    {
        baseValveType.setUpdateTime(DateUtils.getNowDate());
        return baseValveTypeMapper.updateById(baseValveType);
    }

    /**
     * 删除阀门型号数据对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBaseValveTypeByIds(String ids)
    {
        return baseValveTypeMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 导入阀门类型信息数据
     *
     * @param valveTypeList 阀门类型信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importBaseValveType(List<BaseValveType> valveTypeList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(valveTypeList) || valveTypeList.size() == 0)
        {
            throw new BusinessException("导入阀门类型信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseValveType valveType : valveTypeList)
        {
            try
            {
                //根据厂商名字查询厂商信息
                QueryWrapper<BaseFactory> factoryQueryWrapper = new QueryWrapper<BaseFactory>();
                factoryQueryWrapper.eq("factory_name",valveType.getFactoryName());
                BaseFactory baseFactory = baseFactoryMapper.selectOne(factoryQueryWrapper);
                if(baseFactory!=null){
                    valveType.setFactoryId(baseFactory.getFactoryId());
                }

                //查询字典阀门类型是否存在
                QueryWrapper<SysDictData> dataQueryWrapper = new QueryWrapper<SysDictData>();
                dataQueryWrapper.eq("dict_type","valve_model");
                dataQueryWrapper.eq("dict_label", valveType.getTypeModel());
                SysDictData model = dictDataMapper.selectOne(dataQueryWrapper);
                if(model!=null){
                    valveType.setTypeModel(model.getDictValue());
                }else{
                    valveType.setTypeModel(null);
                }

                dataQueryWrapper = new QueryWrapper<SysDictData>();
                //查询字典通信协议是否存在
                dataQueryWrapper.eq("dict_type","valve_agree");
                dataQueryWrapper.eq("dict_label", valveType.getTypeAgree());
                SysDictData agree = dictDataMapper.selectOne(dataQueryWrapper);
                if(agree!=null){
                    valveType.setTypeAgree(agree.getDictValue());
                }else{
                    valveType.setTypeAgree(null);
                }

                //查询阀门类型是否存在
                QueryWrapper<BaseValveType> typeQueryWrapper = new QueryWrapper<BaseValveType>();
                typeQueryWrapper.eq("type_name",valveType.getTypeName());
                BaseValveType valve = baseValveTypeMapper.selectOne(typeQueryWrapper);
                if (StringUtils.isNull(valve))
                {
                    valveType.setCreateBy(operName);
                    valveType.setCreateTime(DateUtils.getNowDate());
                    this.insertBaseValveType(valveType);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、阀门类型 " + valveType.getTypeName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    valveType.setUpdateBy(operName);
                    valveType.setUpdateTime(DateUtils.getNowDate());
                    this.updateBaseValveType(valveType);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、阀门类型 " + valveType.getTypeName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、阀门类型 " + valveType.getTypeName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、阀门类型 " + valveType.getTypeName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验厂商代码是否唯一
     *
     * @param baseValveType 厂商信息
     * @return 结果
     */
    @Override
    public String checkValveTypeCodeUnique(BaseValveType baseValveType)
    {
        Long typeId = StringUtils.isNull(baseValveType.getTypeId()) ? -1L : baseValveType.getTypeId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type_name",baseValveType.getTypeName());
        BaseValveType valveType = baseValveTypeMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(valveType) && valveType.getTypeId().longValue() != typeId.longValue())
        {
            return UserConstants.VALVE_TYPE_NOT_UNIQUE;
        }
        return UserConstants.VALVE_TYPE_UNIQUE;
    }
}
